<template>
  <div>
    <div class="card-header">
      <h2 v-if="productId">修改产品</h2>
      <h2 v-else>新增产品</h2>
    </div>
    <div class="card-body " >
      <Form :label-width="80">
        <FormItem label="所属类别">
          <Cascader :data="categories" v-model="categoriesSelect" placeholder="请选择类目..." ></Cascader>
        </FormItem>
        <FormItem label="所属品牌">
          <Select v-model="brandSelect" clearable placeholder="请选择品牌...">
            <Option v-for="item in brandList" :value="item.id" :key="item.id">{{ item.name }}</Option>
          </Select>
        </FormItem>
        <br><p style="font-size: 16px" v-if="majorProperties.length">关键属性参数</p> <br>
        <FormItem v-for="attribute in majorProperties" :label="attribute.name" :key="attribute.name">
          <Input v-model="attribute.value"/>
        </FormItem>
        <br><p style="font-size: 16px"  v-if="productAttributes.length">通用属性参数</p> <br>
        <FormItem v-for="attribute in productAttributes" :label="attribute.name" :key="attribute.name">
          <Input :value="attribute.value.join(',')" @on-blur="attribute.value = $event.target.value.replace(/，/g, ',').split(',')" type="textarea" :autosize="{minRows: 1,maxRows: 5}" placeholder="请输入参数多个以,隔开"/>
        </FormItem>
        <br><p style="font-size: 16px">规格属性参数</p> <br>
        <template v-for="(attribute, index) in specifications">
          <FormItem  label="属性名称" :key="index">
            <Input v-model="attribute.name" placeholder="请输入属性名称..." />
          </FormItem>
          <FormItem label="属性值" :key="index+'11'">
            <Input :value="attribute.value.join(',')" @on-blur="attribute.value = $event.target.value.replace(/，/g, ',').split(',')" type="textarea" :autosize="{minRows: 2,maxRows: 5}" :placeholder="'请输入'+attribute.name+'属性值以,分割'"></Input>
          </FormItem>
          <FormItem :key="index+'22'">
            <Button type="dashed" size="small" long @click="handleDelete(index)" icon="minus-round">删除规格属性</Button>
          </FormItem>
          <br :key="index+'33'">
        </template>
        <FormItem >
          <Button type="dashed" long @click="handleAdd" icon="plus-round">新增规格属性</Button>
        </FormItem>
        <FormItem>
          <Button type="primary" @click="saveOrModifyAction">保存</Button>
          <Button type="ghost" style="margin-left: 8px">Cancel</Button>
        </FormItem>
      </Form>
    </div>
  </div>

</template>
<script>
import {save, modify, findById} from '../../api/product/productApi'
import getCategoriesTree from '../../api/product/categoriesApi'
import listBrands from '../../api/product/brandsApi'
import getTemplateByCategoryId from '../../api/product/productTemplateApi'
export default {
  data () {
    return {
      productId: 0,
      categories: [],
      brandList: [],
      categoriesSelect: [],
      brandSelect: undefined,
      majorProperties: [], // {name: '型号',value: ''}
      productAttributes: [], // {name: 'test',value: ['黑色', '白色', '粉色', '灰色']}
      specifications: [] // {name: 'test',value: ['黑色', '白色', '粉色', '灰色']}
    }
  },
  mounted () {
    this.productId = this.$route.query.productId
    this.initBrandAndCategories(() => {
      if (this.productId) {
        this.loadData(this.productId)
      }
    })
  },
  methods: {
    initBrandAndCategories (cb) {
      getCategoriesTree(res => {
        this.categories = res
        cb()
      })
      listBrands(res => {
        this.brandList = res
      })
    },
    loadData (productId) {
      findById(productId, res => {
        this.brandSelect = res.brandId
        let categoriesSelect = utils.init(this.categories).search(res.categoryId).split(',').map(o => parseInt(o))
        this.categoriesSelect = categoriesSelect
        setTimeout(() => {
          this.majorProperties = res.majorProperties
          this.productAttributes = res.productAttributes
        }, 800)
        this.specifications = res.specifications
      })
    },
    handleAdd () {
      this.specifications.push({
        name: '',
        value: []
      })
    },
    handleDelete (index) {
      this.specifications.splice(index, 1)
    },
    saveOrModifyAction () {
      let product = {
        brandId: this.brandSelect,
        categoryId: this.categoriesSelect[this.categoriesSelect.length - 1],
        enable: true,
        majorProperties: this.majorProperties,
        productAttributes: this.productAttributes,
        specifications: this.specifications
      }
      if (this.productId) {
        modify(this.productId, product, _ => this.$Message.success('修改产品成功'), _ => this.$Message.error('修改产品失败'))
      } else {
        save(product, _ => this.$Message.success('添加产品成功'), _ => this.$Message.error('添加产品失败'))
      }
    }
  },
  watch: {
    'categoriesSelect' (val) {
      let leafNode = val[val.length - 1]
      getTemplateByCategoryId(leafNode, res => {
        if (res) {
          this.majorProperties = res.majorProperties.map(name => ({name, value: []}))
          this.productAttributes = res.attributes.map(name => ({name, value: []}))
        } else {
          this.majorProperties = []
          this.productAttributes = []
        }
      })
    },
    '$route' (to) {
      this.productId = to.query.productId
      console.log('------')
      if (!this.productId) {
        this.categoriesSelect = []
        this.brandSelect = undefined
        this.majorProperties = []
        this.productAttributes = []
        this.specifications = []
      }
    }
  }
}
const utils = {
  map: {},
  init (categories) {
    this.map = new Map()
    this.leafNodeParentInfo(categories)
    return this
  },
  search (id) {
    let node = this.map.get(id)
    if (node.pid) {
      return this.search(node.pid) + ',' + id
    }
    return id
  },
  leafNodeParentInfo (categories) {
    if (categories) {
      this.setPID(categories, 0)
    }
  },
  setPID (categories, pid) {
    for (let category of categories) {
      this.map.set(category.id, category)
      category.pid = pid
      if (category.children) {
        this.setPID(category.children, category.id)
      }
    }
  }
}
</script>
